<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item,index) in suggessList"
      :key="index"
      icon="search"
      @click="$emit('onSearch',item)"
    >
      <span
        slot="title"
        v-html="highLight(item)"
      ></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggesstion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggestion',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggessList: []
    }
  },
  methods: {
    async getSuggesstion (q) {
      try {
        const { data } = await getSearchSuggesstion(q)
        this.suggessList = data.data.options
      } catch (err) {
        console.log(err)
      }
    },
    highLight (item) {
      const htmlStr = `<span style="color: #7bb9fb">${this.value}</span>`
      const reg = new RegExp(this.value, 'ig')
      return item.replace(reg, htmlStr)
    }
  },
  watch: {
    value: {
      handler: debounce(function () {
        this.getSuggesstion(this.value)
      }, 200),
      immediate: true
    }
  }
}
</script>

<style>
</style>
